/*
 * @Author: zhangyang
 * @Date: 2020-12-09 17:21:19
 * @LastEditTime: 2022-01-23 14:34:14
 * @Description: 页面权限控制
 */
import router from './route/index';
import commonRoutes from './route/common/index';
import NProgress from 'nprogress';

import { getToken } from './util/auth';
import { ROLE_ROUTE } from './store';
import type { RouteLocationNormalized } from 'vue-router';

NProgress.configure({
  showSpinner: false
});

const getCommonRoutes = () => {
  const routesArr: string[] = [];
  for (const route of commonRoutes) {
    if (route.children?.length) {
      for (const sub of route.children) {
        routesArr.push(sub.path);
      }
    } else {
      routesArr.push(route.path);
    }
  }
  return routesArr;
};

const hasPermission = (route: RouteLocationNormalized | string) => {
  const roleRoute = ROLE_ROUTE.value.concat(getCommonRoutes());
  if (typeof route === 'string') {
    return roleRoute.includes(route);
  }
  return roleRoute.includes(route.path) || roleRoute.includes(route.fullPath);
};

/**
 * 前置导航守卫
 */
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = (to.meta.title as string) || '小黑后台';

  // 此处添加鉴权
  if (!getToken().token && to.name !== 'login') {
    await ElMessageBox.confirm('未登录或登录信息过期，请先去登录', '提示', {
      type: 'error',
      showCancelButton: false,
      closeOnClickModal: false,
    }).catch(() => null);
    next({
      name: 'login',
      query: {
        redirect: to.path
      }
    });

    NProgress.done();
  } else if (!hasPermission(to)) {
    // 具体页面权限 map 判断
    ElMessage.error('暂时无权访问该页面，请勿进行恶意操作');
    next(from.path);
  } else {
    next();
  }
});

/**
 * 后置导航守卫
 */
router.afterEach(() => {
  NProgress.done();
});
